<template>
  <div class="goods-image">
    <!-- 放置大图 -->
    <div
      v-show="!isOutside"
      class="large"
      :style="[
        {
          backgroundImage: picture && `url(${picture[index]})`,
          backgroundPosition: `-${pos.left * 2}px -${pos.top * 2}px`
        }
      ]"
    ></div>
    <div ref="target" class="middle">
      <img :src="picture && picture[index]" alt="" />
      <!-- 蒙层容器 -->
      <div
        ref="mask"
        :style="{ left: `${pos.left}px`, top: `${pos.top}px` }"
        v-if="!isOutside"
        class="layer"
      ></div>
    </div>
    <!-- 小图片 -->
    <ul class="small">
      <li
        v-for="(img, i) in picture"
        :key="i"
        :class="{ active: i === index }"
        @mouseenter="change(i)"
      >
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script setup>
import { defineProps, reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
defineProps({
  picture: {
    type: Array,
    required: true
  }
})
const index = ref(0)
const change = (i) => {
  index.value = i
}

// 放大镜
const target = ref(null)
const mask = ref(null)
const { isOutside, elementX, elementY } = useMouseInElement(target)
const pos = reactive({ left: 0, top: 0 })
watch([elementX, elementY], () => {
  // x轴
  if (elementX.value < 100) {
    pos.left = 0
  } else if (elementX.value > 300) {
    pos.left = 200
  } else {
    pos.left = elementX.value - 100
  }

  // y轴
  if (elementY.value < 100) {
    pos.top = 0
  } else if (elementY.value > 300) {
    pos.top = 200
  } else {
    pos.top = elementY.value - 100
  }
})
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
